<?php

namespace App\Console\Commands;

use Encore\Admin\Admin;
use Encore\Admin\Auth\Database\Administrator;
use Illuminate\Console\Command;
use DB;

class Loss extends Command {

    protected $signature = 'stloss:run {auto=n}';
    protected $description = '学员流失脚本';

    public function __construct(){
        parent::__construct();
    }
	/**
	 * [判断处理方式]
	 */
    public function handle() {
		$params = $this->arguments();
		$this->init($params);
		if($params['auto'] === "y"){
			$this->doRun();
		}else{
			$tips = 'the time is between '.$this->s_time.' ~ '.$this->e_time.','."\n";
			$tips .=' 第'.$this->week."周\n";
			$tips .=' "y" or "yes" to continue';
			if($this->confirm($tips)){
			    $this->doRun();
			}
		}
    }
	/**
	 * [数据初始化]
	 */
	private function init($params) {
		if($params['auto'] === "y"){
			$this->e_time = date("Y-m-d H:i:s",time());
			$this->s_time = date("Y-m-d H:i:s",(strtotime($this->e_time) - 7*24*3600));
		}else{
			$this->e_time = $this->ask('please inupt the end time,format like "YmdHis"');
			$this->e_time = date("Y-m-d H:i:s",strtotime($this->e_time));
			$this->s_time = date("Y-m-d H:i:s",(strtotime($this->e_time) - 7*24*3600));
		}
		$term_info = DB::table("terms")
			->orderBy('start_date','asc')
			->first();
		$term_info = json_decode(json_encode($term_info),true);
		if(empty($term_info)){
			echo " warning:can not find term info,please check table:`terms` first\n";
			exit;
		}
		$this->term_start_date = $term_info['start_date']." 00:00:00";
		$this->season = $term_info['season'];
		$this->year = $term_info['year'];
		$this->week = (int)ceil((strtotime($this->e_time) - strtotime($this->term_start_date))/3600/24/7);
	}
	/**
	 * [执行]
	 */
	private function doRun() {
		$error_count = 0;
		$str = "running:\n";
		$str .= " [".$this->s_time.",".$this->e_time."]\n ";
		$str .= $this->year."年,第".$this->season."季,第".$this->week."周\n";
		echo $str;
		$squads = DB::table("squads")->pluck("id");
		$bar = $this->output->createProgressBar(sizeof($squads));
		$bar->start();
		DB::beginTransaction();
		try {
			foreach($squads as $s){
				$lost_num = DB::table('applys')
					->whereIn('type',['2','3'])
					->whereBetween('sp_time',[$this->s_time,$this->e_time])
					->where([
						'status' => '1',
						'squad_id' => $s
					])->count();
				$st_num = DB::table('students')
					->where([
						'status' => '1',
						'squad_id' => $s
					])->count();
				$data = [
					'year' => $this->year,
					'season' => $this->season,
					'week' => $this->week,
					'squad_id' => $s,
					'wastage_num' => $lost_num,
					'st_num' => $st_num+$lost_num,
					'c_time' => date("YmdHis",time())
				];
				if($st_num+$lost_num == 0){
	                $data['wastage_rate'] = 0;
	            }else{
	                $data['wastage_rate'] = $lost_num/($st_num+$lost_num);
	            }
				$where = [
					"squad_id" => $s,
					"year" => $this->year,
					"season" => $this->season,
					"week" => $this->week
				];
				$check = DB::table('artisan_stloss')->where($where)->count();
				if($check){
					DB::table('artisan_stloss')->where($where)->update($data);
				}else{
					DB::table("artisan_stloss")->insert($data);
				}
				$bar->advance();
			}
			DB::commit();
		} catch (\Exception $e) {
			$error_count += 1;
			echo "\n error:".$e->getMessage()."\n";
			DB::rollback();
			exit;
		}
		$bar->finish();
		// 输出结果
		echo "\n Completed!(errors:".$error_count.")\n";
	}
}
